package com.uit3j.cloud.auth.application;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSource {
    //当前电影票余量
    private static int currentTickets = 30;

    //加锁确保多线程场景下的线程安全
    private static final Lock lock = new ReentrantLock();

    /**
     * 卖票
     *
     * @return 当前电影票余量
     */
    public static int saleTickets() {
        lock.lock();
        try {
            if (currentTickets > 0) {
                //模拟卖票
                currentTickets--;
                if (currentTickets == 0) {
                    //票余量为 0 停止售卖
                    System.out.println(
                        Thread.currentThread().getName() + "窗口出票成功！"
                            + "当前票余量：" + currentTickets
                            + " 今日票已卖完！");
                } else {
                    System.out.println(
                        Thread.currentThread().getName() + "窗口出票成功！"
                            + "当前票余量：" + currentTickets);
                }
            } else {
                //票余量为 0 停止售卖
                System.out.println(Thread.currentThread().getName() + "窗口：今日票已卖完！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return currentTickets;
    }

}
